import { login as loginAPI } from "@/api";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { dynamicRoutes, constantRoutes, randomRoutes } from "@/router/routes";
import { cloneDeep } from "lodash";
import router from "@/router";
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    buttons: [],
    routes: [], // 本用户所有的路由,包括了固定的路由和下面的addRouters
    asyncRoutes: [], // 本用户的角色赋予的新增的动态路由
  };
};

// 数组深拷贝
const deepClone = (item) => {
  const typeOf = ["function", "object"].includes(typeof item);
  if (!typeOf) {
    return item;
  }
  if (typeof item == "function") {
    return eval(item.toString());
  }
  const type = item instanceof Array ? [] : {};
  for (const key in item) {
    type[key] = deepClone(item[key]);
  }
  return type;
};

// 过滤路由
const filterRoutes = (dynamicRoutes, routes) => {
  return dynamicRoutes.filter((item) => {
    if (item.children) filterRoutes(item.children, routes);
    return routes.includes(item.name);
  });
};

const state = getDefaultState();

const mutations = {
  SET_USER: (state, userInfo) => {
    state.name = userInfo.name; // 用户名
    state.avatar = userInfo.avatar; // 头像
    state.roles = userInfo.roles; // 角色列表
    state.buttons = userInfo.buttons; // 按钮权限列表
  },

  SET_TOKEN(state, token) {
    state.token = token;
  },

  RESET_USER(state) {
    Object.assign(state, getDefaultState());
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      loginAPI
        .login(username, password)
        .then((result) => {
          const { data } = result;
          commit("SET_TOKEN", data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    const { data } = await loginAPI.getInfo();
    commit("SET_USER", data);
    let routes = filterRoutes(cloneDeep(dynamicRoutes), data.routes);
    const dynamicAddRoutes = routes.concat(randomRoutes);
    console.log(dynamicAddRoutes);
    dynamicAddRoutes.forEach((item) => router.addRoute(item));
    state.routes = constantRoutes.concat(dynamicAddRoutes);
  },

  /* 
  重置用户信息
  */
  async resetUser({ commit, state }) {
    // 如果当前是登陆的, 请求退出登陆
    if (state.name) {
      await loginAPI.logout();
    }
    // 提交重置用户信息的mutation
    commit("RESET_USER");
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
